import 'package:flutter/material.dart';
import '../models/article.dart';
import '../models/company.dart';
import '../services/api_service.dart';
import '../config/app_config.dart';

/// 资讯数据状态管理
class ArticleProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  
  // 资讯列表
  List<Article> _articleList = [];
  int _total = 0;
  bool _loading = false;
  
  // 公司列表
  List<Company> _companyList = [];
  int? _selectedCompanyId;
  
  // 资讯类型筛选
  String? _selectedArticleType;
  
  // 当前资讯详情
  Article? _currentArticle;
  
  // Getters
  List<Article> get articleList => _articleList;
  int get total => _total;
  bool get loading => _loading;
  List<Company> get companyList => _companyList;
  int? get selectedCompanyId => _selectedCompanyId;
  String? get selectedArticleType => _selectedArticleType;
  Article? get currentArticle => _currentArticle;
  
  /// 切换收藏（列表项或详情）
  Future<bool> toggleFavorite(int articleId) async {
    try {
      final res = await _apiService.toggleFavorite(articleId: articleId);
      final isFavorited = res.data['data']?['isFavorited'] ?? res.data['isFavorited'] ?? false;
      // 更新列表
      for (final a in _articleList) {
        if (a.articleId == articleId) {
          a.isFavorite = isFavorited;
          break;
        }
      }
      // 更新详情
      if (_currentArticle?.articleId == articleId) {
        _currentArticle!.isFavorite = isFavorited;
      }
      notifyListeners();
      return isFavorited;
    } catch (e) {
      debugPrint('切换收藏失败: $e');
      rethrow;
    }
  }
  
  /// 检查是否已收藏
  Future<bool> checkFavorite(int articleId) async {
    try {
      final res = await _apiService.checkFavorite(articleId: articleId);
      return res.data['data'] ?? false;
    } catch (e) {
      debugPrint('检查收藏状态失败: $e');
      return false;
    }
  }
  
  /// 获取资讯列表
  Future<void> fetchArticleList({
    int pageNum = 1,
    int pageSize = AppConfig.pageSize,
    bool refresh = false,
  }) async {
    try {
      _loading = true;
      if (refresh) {
        notifyListeners();
      }
      
      final response = await _apiService.getArticleList(
        pageNum: pageNum,
        pageSize: pageSize,
        companyId: _selectedCompanyId,
        articleType: _selectedArticleType,
        status: '3', // 只获取已完成的资讯 (0待处理 1AI处理中 2TTS生成中 3已完成 4失败)
      );
      
      // 若依框架的 TableDataInfo 格式: { code: 200, msg: '', rows: [...], total: 100 }
      final data = response.data;
      final List<dynamic> rows = data['rows'] ?? [];
      
      if (pageNum == 1) {
        _articleList = rows.map((json) => Article.fromJson(json)).toList();
      } else {
        _articleList.addAll(rows.map((json) => Article.fromJson(json)).toList());
      }
      
      _total = data['total'] ?? 0;
      _loading = false;
      notifyListeners();
    } catch (e) {
      _loading = false;
      notifyListeners();
      rethrow;
    }
  }
  
  /// 获取资讯详情
  Future<void> fetchArticleDetail(int articleId) async {
    try {
      final response = await _apiService.getArticleDetail(articleId);
      // 若依框架的 AjaxResult success() 格式: { code: 200, msg: '', data: {...} }
      _currentArticle = Article.fromJson(response.data['data']);
      notifyListeners();
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取公司列表
  Future<void> fetchCompanyList() async {
    try {
      final response = await _apiService.getCompanyList();
      // 若依框架的 TableDataInfo 格式: { code: 200, msg: '', rows: [...], total: 100 }
      final List<dynamic> rows = response.data['rows'] ?? [];
      
      _companyList = rows.map((json) => Company.fromJson(json)).toList();
      
      // 默认选中第一个公司（如果尚未选择且有数据）
      if (_selectedCompanyId == null && _companyList.isNotEmpty) {
        _selectedCompanyId = _companyList.first.companyId;
      }
      // 默认选中第一个资讯类型（如果尚未选择）
      _selectedArticleType ??= 'earnings_call';
      
      // 批量加载公司Logo
      for (var company in _companyList) {
        try {
          final fileRes = await _apiService.getFileByBiz('company_logo', company.companyId);
          if (fileRes.data['data'] != null) {
            final fileId = fileRes.data['data']['fileId'];
            company.logoUrl = _apiService.getFileViewUrl(fileId);
          }
        } catch (e) {
          // Logo加载失败不影响公司列表显示
          debugPrint('公司${company.companyId}的Logo加载失败: $e');
        }
      }
      
      notifyListeners();
    } catch (e) {
      rethrow;
    }
  }
  
  /// 选择公司筛选
  void selectCompany(int? companyId) {
    _selectedCompanyId = companyId;
    notifyListeners();
    // 重新加载列表
    fetchArticleList(pageNum: 1, refresh: true);
  }
  
  /// 选择资讯类型筛选
  void selectArticleType(String? typeValue) {
    _selectedArticleType = typeValue;
    notifyListeners();
    // 重新加载列表
    fetchArticleList(pageNum: 1, refresh: true);
  }
  
  /// 重置
  void reset() {
    _articleList = [];
    _total = 0;
    _selectedCompanyId = null;
    _selectedArticleType = null;
    _currentArticle = null;
    notifyListeners();
  }
}

